
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include "../iface/debug.h"
#include "../utils/BaseConvert.h"
#include "../utils/StringUtils.h"
#include "ECDSAPublicKey.h"

/** Constructor for a blank ECDSA public key. */
ECDSAPublicKey::ECDSAPublicKey()
{
   key = NULL;
   keyname = NULL;
}

/** Constructor for a blank ECDSA public key with a name.
 * 
 * @param name The name to attach to the blank key. */
ECDSAPublicKey::ECDSAPublicKey(const char *name)
{
   key = NULL;
   keyname = NULL;
   setKeyName(name);
}

/** Copy constructor for an ECDSA public key.
 * 
 * @param other The ECDSA public key to copy from. */
ECDSAPublicKey::ECDSAPublicKey(const ECDSAPublicKey &other)
{
   key = EC_KEY_new();
   if (key == NULL)
   {
      errprint("EC_KEY_new failed");
      return;
   }
   if (copyECDSASSLPublicKey(key, other.key))
   {
      errprint("EC_KEY_new failed");
      return;
   }
   keyname = NULL;
   setKeyName(other.keyname);
}

/** Construct an ECDSA public key from an ECDSA public key in PEM
 * encoded PKCS #8 text format.
 * 
 * @param pemtext The PEM encoded PKCS #8 text that represents an
 * ECDSA public key, from which this key is to be constructed.
 * 
 * @param name The name to be attached to the key, once
 * constructed. */
ECDSAPublicKey::ECDSAPublicKey(const char *pemtext, const char *name)
{
   importKeyFromASCII(pemtext, name);
}

/** Construct an ECDSA public key from an ECDSA public key in SSL
 * format.
 * 
 * @param pubkey The SSL format ECDSA public key to construct this key
 * from.
 * 
 * @param name The name to be attached to the key, once
 * constructed. */
ECDSAPublicKey::ECDSAPublicKey(EC_KEY *pubkey, const char *name)
{
   key = EC_KEY_new();
   if (key == NULL)
   {
      errprint("EC_KEY_new failed");
      return;
   }
   if (copyECDSASSLPublicKey(key, pubkey))
   {
      errprint("EC_KEY copy failed");
      SSLCheckError(0);
      return;
   }
   keyname = NULL;
   setKeyName(name);
}

/** Copy constructor for an ECDSA public key.
 * 
 * @param other The ECDSA public key to copy from.
 * 
 * @return Itself. */
ECDSAPublicKey &ECDSAPublicKey::operator=(const ECDSAPublicKey &other)
{
   key = EC_KEY_new();
   if (key == NULL)
   {
      errprint("EC_KEY_new failed");
      return *this;
   }
   if (copyECDSASSLPublicKey(key, other.key))
   {
      errprint("EC_KEY copy failed");
      SSLCheckError(0);
      return *this;
   }
   keyname = NULL;
   setKeyName(other.keyname);
   return *this;
}

/** Destructor for the ECDSA public key. */
ECDSAPublicKey::~ECDSAPublicKey()
{
   if (key) EC_KEY_free(key);
   key = NULL;
   if (keyname) free((void *)keyname);
   keyname = NULL;
}

/** Get a copy of the public key as an SSL format object.
 * 
 * @param[out] pubkey A pointer to a place to put a pointer to the new
 * SSL format ECDSA public key which is a copy of this key. The
 * responsibility for freeing the new SSL format ECDSA public key is
 * transferred to the caller.
 * 
 * @return Returns zero on success, non-zero on failure. */
int ECDSAPublicKey::getSSLKeyComponents(EC_KEY **pubkey) const
{
   *pubkey = EC_KEY_new();
   if ((*pubkey) == NULL)
   {
      errprint("EC_KEY_new failed");
      return -1;
   }
   return copyECDSASSLPublicKey(*pubkey, key);
}

/** Get a copy of the public key in PEM encoded PKCS #8 text format.
 * 
 * @param[out] pemtext A pointer to a place to put a pointer to the
 * exported key in PEM encoded PKCS #8 text format. The responsibility
 * for freeing the new string is transferred to the caller.
 * 
 * @param password A password which may be required to unlock the key.
 * 
 * @return Returns zero on success, non-zero on failure. */
int ECDSAPublicKey::getPEMKeyData(char **pemtext, const char *password) const
{
   char *data;
   int damt;
   char *dbuf = NULL;
   int retval = 0;
   EVP_PKEY *epkey = EVP_PKEY_new();
   EVP_PKEY_set1_EC_KEY(epkey, key);
   BIO *bo = BIO_new(BIO_s_mem());
   if (!PEM_ASN1_write_bio((i2d_of_void *)i2d_EC_PUBKEY, PEM_STRING_ECDSA_PUBLIC, bo, (char *)key, (password) ? EVP_des_ede3_cbc() : NULL, NULL, 0, 0, (void *)password))
//   if (!PEM_write_bio_PUBKEY(bo, epkey))
   {
      retval = 1;
      errprint("could not export public key");
      SSLCheckError();
      goto bioshutdown;
   }
   SSLCheckError();
   damt = BIO_get_mem_data(bo, &data);
   *pemtext = (char *)malloc(sizeof(char)*(damt+1));
   memcpy(*pemtext, data, sizeof(char)*(damt+1));
   (*pemtext)[damt] = '\0';
bioshutdown:
   BIO_set_close(bo, BIO_CLOSE);
   BIO_free(bo);
   EVP_PKEY_free(epkey);
   return retval;
}

/** Export the ECDSA public key as the binary encoding of the SSH key
 * format in the authorized_keys file.
 * 
 * @param[out] blob A pointer to the place where the pointer to the
 * binary key blob is to be put. The responsibility for freeing the
 * new buffer is transferred to the caller.
 * 
 * @param[out] reallength A pointer to where the write the length of
 * the blob in bytes.
 * 
 * @return Returns zero on success, non-zero on failure. */
int ECDSAPublicKey::getSSHKeyBlob(char **blob, int *reallength) const
{
   unsigned char keyheader[23] = {
      0x00,0x00,0x00,0x13, 'e', 'c', 'd', 's', 'a', '-',
       's', 'h', 'a', '2', '-', 'n', 'i', 's', 't', 'p',
       '2', '5', '6' };
   unsigned char curvename[12] = {
      0x00,0x00,0x00,0x08, 'n', 'i', 's', 't', 'p', '2',
       '5', '6' };
   char realnum[4];
   int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(key));
   switch (nid)
   {
      default:
      case NID_X9_62_prime256v1: sprintf(realnum, "256"); break;
      case NID_secp384r1: sprintf(realnum, "384"); break;
      case NID_secp521r1: sprintf(realnum, "521"); break;
   }
   memcpy(&(keyheader[20]), realnum, sizeof(char)*3);
   memcpy(&(curvename[9]), realnum, sizeof(char)*3);
   int enclen = 23 + 12;
   size_t enc_point_len = EC_POINT_point2oct(EC_KEY_get0_group(key),
                                             EC_KEY_get0_public_key(key),
                                             POINT_CONVERSION_UNCOMPRESSED,
                                             NULL, 0, NULL);
   unsigned char *enc_point_buf = (unsigned char *)malloc(sizeof(unsigned char)*enc_point_len);
   size_t enc_point_len2 = EC_POINT_point2oct(EC_KEY_get0_group(key),
                                              EC_KEY_get0_public_key(key),
                                              POINT_CONVERSION_UNCOMPRESSED,
                                              enc_point_buf, enc_point_len, NULL);
   enclen += (4 + enc_point_len);
   char *encode = (char *)malloc(sizeof(char)*enclen);
   memcpy(encode, keyheader, sizeof(char)*23);
   memcpy(&(encode[23]), curvename, sizeof(char)*12);
   encode[23 + 12 + 0] = (unsigned char)(enc_point_len >> 24);
   encode[23 + 12 + 1] = (unsigned char)(enc_point_len >> 16);
   encode[23 + 12 + 2] = (unsigned char)(enc_point_len >>  8);
   encode[23 + 12 + 3] = (unsigned char)(enc_point_len      );
   memcpy(&(encode[23 + 12 + 4]), enc_point_buf, sizeof(char)*enc_point_len);
   if (reallength) *reallength = 23 + 12 + 4 + enc_point_len;
   if (blob) *blob = encode;
   return 0;
}

/** Export the ECDSA public key as a line of text that can be added to
 * the SSH authorized_keys file.
 * 
 * @param[out] textblob A pointer to the place where the pointer to
 * the text-encoded labelled key blob is to be put. This is the final
 * line that can be added to authorized_keys. The responsibility for
 * freeing the new string is transferred to the caller.
 * 
 * @param keylabel The label to go on the key on the standardised line
 * of text.
 * 
 * @return Returns zero on success, non-zero on failure. */
int ECDSAPublicKey::getSSHKeyBlob(char **textblob, const char *keylabel) const
{
   int enclen = 0;
   char *encode;
   if (getSSHKeyBlob(&encode, &enclen) != 0) return -1;
   char *base64string = BaseConvert::convertBytesToBase64(encode, enclen);
   free(encode);
   char *finalstring = StringUtils::varprintf("ssh-dss %s %s", base64string, keylabel);
   free(base64string);
   if (textblob) *textblob = finalstring;
   return 0;
}

/** Compare the key to another PublicKey, and see if they are equal.
 * 
 * @param pubkey PublicKey that is to be tested to see if these are
 * equal.
 * 
 * @return 1 if they match, 0 if they do not, and negative values
 * represent errors. */
int ECDSAPublicKey::compareKeyEqual(PublicKey *pubkey) const
{
   if (pubkey == NULL)
   {
      errprint("comparing against NULL key");
      return 0;
   }
   switch (pubkey->getKeyType())
   {
      case KEY_TYPE_PUBLIC_ECDSA:
      {
         EC_KEY *ecdsaKeyOther = NULL;
         ((ECDSAPublicKey *)pubkey)->getSSLKeyComponents(&ecdsaKeyOther);
         EVP_PKEY *evp1 = EVP_PKEY_new();
         EVP_PKEY *evp2 = EVP_PKEY_new();
         EVP_PKEY_set1_EC_KEY(evp1, key);
         EVP_PKEY_set1_EC_KEY(evp2, ecdsaKeyOther);
         int retval = EVP_PKEY_cmp(evp1, evp2);
         EVP_PKEY_free(evp1);
         EVP_PKEY_free(evp2);
         EC_KEY_free(ecdsaKeyOther);
         SSLCheckError();
         switch (retval)
         {
            case -2:
               errprint("key compare operation not supported (EVP_PKEY_cmp())");
               break;
            case -1:
               errprint("tried to compare different key types (EVP_PKEY_cmp())");
               return 0;
            case 0:
               return 0;
            case 1:
               return 1;
         }
         return 0;
      }
      default:
      {
         return 0;
         break;
      }
   }
}

/** Copy an SSL format public key (or the public key part of a full
 * private key in SSL format, as the public key is simply a subset of
 * the private key data).
 * 
 * @param[out] dst Pointer to an initialised blank SSL format ECDSA
 * key to copy into.
 * 
 * @param src Pointer to an existing SSL format ECDSA public key to
 * copy from.
 * 
 * @return Returns zero on success, non-zero on failure. */
int ECDSAPublicKey::copyECDSASSLPublicKey(EC_KEY *dst, EC_KEY *src)
{
   if (dst == NULL) { errprint("NULL public key destination"); return -1; }
   if (src == NULL) { errprint("NULL public key source"); return -1; }
   if (EC_KEY_set_group(dst, EC_KEY_get0_group(src)) == 0)
   {
      errprint("Failed to copy%s key group", (EC_KEY_get0_group(src)) ? "" : " NULL");
      return -1;
   }
   if (EC_KEY_set_public_key(dst, EC_KEY_get0_public_key(src)) == 0)
   {
      errprint("Failed to copy%s public key", (EC_KEY_get0_public_key(src)) ? "" : " NULL");
      return -1;
   }
   return 0;
}

/** Import and name an ECDSA public key from an ECDSA public key in
 * encrypted PEM format PKCS #8.
 * 
 * @param pemtext The PEM encoded PKCS #8 text that represents an
 * ECDSA public key, from which this key is to be constructed.
 * 
 * @param password The password to decrypt the PEM encoded PKCS #8
 * text that represents the ECDSA public key.
 * 
 * @return Returns zero on success, non-zero on failure. */
int ECDSAPublicKey::importPublicKeyWithOptionalPassword(const char *pemtext, const char *password)
{
   if (!key) key = EC_KEY_new();
   int retval = 0;
   BIO *bo = BIO_new_mem_buf((void *)pemtext, -1);
   SSLCheckError();
   if (!PEM_ASN1_read_bio((d2i_of_void *)d2i_EC_PUBKEY, PEM_STRING_ECDSA_PUBLIC, bo, (void **)(&key), 0, (void *)password))
   {
      retval = 1;
      errprint("could not import public key");
      key = NULL;
      goto bioshutdown;
   }
bioshutdown:
   BIO_set_close(bo, BIO_CLOSE);
   BIO_free(bo);
   return retval;
}

/** Import an ECDSA public key from some PEM format PKCS #8 text.
 * 
 * @param text The PEM encoded PKCS #8 text that represents an ECDSA
 * public key, from which this key is to be constructed.
 * 
 * @param name The name to be attached to the key.
 * 
 * @return Returns zero on success, non-zero on failure. */
int ECDSAPublicKey::importKeyFromASCII(const char *text, const char *name)
{
   setKeyName(name);
   return importPublicKeyWithOptionalPassword(text, NULL);
}

/** Import and name an ECDSA public key from an ECDSA public key in
 * encrypted PEM format PKCS #8 (the encryption is UNIMPLEMENTED, this
 * is plain text!).
 * 
 * @param text The PEM encoded PKCS #8 text that represents an ECDSA
 * public key, from which this key is to be constructed.
 * 
 * @param password The password to decrypt the PEM encoded PKCS #8
 * text that represents the ECDSA public key.
 * 
 * @param name The name to be attached to the key.
 * 
 * @return Returns zero on success, non-zero on failure. */
int ECDSAPublicKey::importKeyFromASCIIWithPassword(const char *text, const char *password, const char *name)
{
   setKeyName(name);
   return importPublicKeyWithOptionalPassword(text, password);
}

/** Export an ECDSA public key to some PEM format PKCS #8 text.
 * 
 * @param[out] text A pointer to a place to put a pointer to the
 * exported key in PEM encoded PKCS #8 text format. The responsibility
 * for freeing the new string is transferred to the caller.
 * 
 * @return Returns zero on success, non-zero on failure. */
int ECDSAPublicKey::exportKeyToASCII(char **text) const
{
   return getPEMKeyData(text, NULL);
}

/** Export an ECDSA public key to some PEM format PKCS #8 text
 * encrypted with the given password (the encryption is UNIMPLEMENTED,
 * this is plain text!).
 * 
 * @param[out] text A pointer to a place to put a pointer to the
 * exported key in encrypted PEM encoded PKCS #8 text format. The
 * responsibility for freeing the new string is transferred to the
 * caller.
 * 
 * @param password The password to encrypt and decrypt the key with.
 * 
 * @return Returns zero on success, non-zero on failure. */
int ECDSAPublicKey::exportKeyToASCIIWithPassword(char **text, const char *password) const
{
   return getPEMKeyData(text, password);
}
